package emulator.hardware.bits;

public class BitGate extends SharedBit {
	private SharedBit[] control_bits;
	private boolean closed_state;
	private SharedBit[] output_bits;
	
	public BitGate(int count, boolean default_output)
	{
		control_bits = new SharedBit[count];
		output_bits = new SharedBit[count];
		closed_state = default_output;
		
		for (int i = 0; i < count; i++)
		{
			control_bits[i] = new SharedBit();
			output_bits[i] = new SharedBit();
			output_bits[i].setValue(closed_state);
		}
	}
	
	public SharedBit getOutputBit(int index)
	{
		return output_bits[index];
	}
	
	public void setOutputBit(int index, SharedBit bit)
	{
		output_bits[index] = bit;
	}
	
	public SharedBit getControlBit(int index)
	{
		return control_bits[index];
	}

	/* (non-Javadoc)
	 * @see emulator.hardware.bits.SharedBit#getValue()
	 */
	@Override
	public synchronized boolean getValue() {
		return super.getValue();
	}

	/* (non-Javadoc)
	 * @see emulator.hardware.bits.SharedBit#setValue(boolean)
	 */
	@Override
	public synchronized void setValue(boolean value) {
		super.setValue(value);
		updateOutput();
	}

	/* (non-Javadoc)
	 * @see emulator.hardware.bits.SharedBit#toggle()
	 */
	@Override
	public synchronized void toggle() {
		super.toggle();
		updateOutput();
	}

	private void updateOutput() {
		for (int i = 0; i < control_bits.length; i++)
			output_bits[i].setValue(control_bits[i].getValue() ? super.getValue() : closed_state);
	}
}
